<template>
  <div v-if="show" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50" @click.self="close">
    <div class="bg-white rounded-lg shadow-2xl flex flex-col w-2/3 h-[80vh]">
      <!-- Top Bar: Filters -->
      <div class="px-6 py-4 border-b flex items-center gap-4 flex-wrap bg-gray-50 rounded-t-lg">
        <h2 class="text-xl font-bold text-gray-800 mr-4">刷题模式</h2>
        
        <!-- Folder Filter -->
        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700">范围:</label>
          <select v-model="filters.folderId" class="border rounded px-2 py-1 text-sm w-40" @change="reload">
            <option :value="null">全部</option>
            <option v-for="f in folderOptions" :key="f.id" :value="f.id">{{ f.label }}</option>
          </select>
        </div>

        <!-- Plan Filter -->
        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700">复盘:</label>
          <select v-model="filters.inPlan" class="border rounded px-2 py-1 text-sm" @change="reload">
            <option :value="null">全部</option>
            <option :value="true">已加入计划</option>
            <option :value="false">未加入计划</option>
          </select>
        </div>

        <!-- Order Filter -->
        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700">顺序:</label>
          <select v-model="filters.order" class="border rounded px-2 py-1 text-sm" @change="reload">
            <option value="seq">顺序</option>
            <option value="random">乱序</option>
          </select>
        </div>

        <!-- Mode Filter -->
        <div class="flex items-center gap-2 ml-auto">
          <label class="text-sm font-medium text-gray-700">模式:</label>
          <div class="flex border rounded overflow-hidden">
            <button 
              class="px-3 py-1 text-sm" 
              :class="filters.mode === 'browse' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-50'"
              @click="filters.mode = 'browse'"
            >浏览</button>
            <button 
              class="px-3 py-1 text-sm border-l" 
              :class="filters.mode === 'quiz' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-50'"
              @click="filters.mode = 'quiz'"
            >做题</button>
          </div>
        </div>
        
        <button class="text-gray-500 hover:text-gray-700 ml-4" @click="close">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <!-- Main Content -->
      <div class="flex-1 overflow-hidden flex flex-col relative">
        <div v-if="loading" class="absolute inset-0 flex items-center justify-center bg-white/80 z-10">
          <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        </div>

        <div v-if="questions.length === 0 && !loading" class="flex-1 flex items-center justify-center text-gray-500">
          没有找到符合条件的题目
        </div>

        <div v-else-if="currentQuestion" class="flex-1 overflow-y-auto p-8 space-y-8">
          <!-- Question Section -->
          <div class="space-y-4">
            <div class="flex items-center justify-between text-sm text-gray-500">
              <span>来自: {{ currentQuestion.title }}</span>
              <span>{{ currentIndex + 1 }} / {{ questions.length }}</span>
            </div>
            <div class="text-xl font-bold text-gray-900 leading-relaxed">
              {{ currentQuestion.question }}
            </div>
          </div>

          <hr class="border-gray-200" />

          <!-- Answer Section -->
          <div class="space-y-4">
            <!-- Browse Mode: Show Answer directly -->
            <div v-if="filters.mode === 'browse' || showAnswer" class="prose max-w-none bg-gray-50 p-6 rounded-lg border">
              <div class="font-semibold text-gray-700 mb-2">参考答案:</div>
              <div v-html="currentQuestion.answer_html"></div>
            </div>

            <!-- Quiz Mode: Input Area -->
            <div v-if="filters.mode === 'quiz'" class="space-y-4">
              <div v-if="!showAnswer">
                <div class="font-semibold text-gray-700 mb-2">你的回答:</div>
                <RichTextEditor v-model="userAnswer" :height="300" />
                <div class="flex justify-end mt-4">
                  <button 
                    class="px-6 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
                    @click="submitAnswer"
                    :disabled="submitting"
                  >
                    {{ submitting ? '提交中...' : '提交答案' }}
                  </button>
                </div>
              </div>
              
              <!-- After Submit: Show Result and Reference -->
              <div v-else class="space-y-6">
                <div class="bg-blue-50 p-6 rounded-lg border border-blue-100">
                  <div class="font-semibold text-blue-800 mb-2">你的回答:</div>
                  <div class="prose max-w-none" v-html="submittedAnswer"></div>
                </div>
                <div class="flex justify-end">
                   <button class="text-blue-600 hover:underline" @click="resetQuiz">重做本题</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Bottom Bar -->
      <div class="px-6 py-4 border-t bg-gray-50 flex items-center justify-between flex-shrink-0">
        <div class="flex gap-3">
           <button 
             class="px-4 py-2 border rounded bg-white hover:bg-gray-50 flex items-center gap-2"
             @click="openAddToReview"
             :disabled="!currentQuestion"
           >
             <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
             </svg>
             <span>加入复盘计划</span>
           </button>
        </div>

        <div class="flex gap-3">
          <button 
            class="px-6 py-2 border rounded bg-white hover:bg-gray-50 disabled:opacity-50"
            @click="prev"
            :disabled="currentIndex <= 0"
          >
            上一题
          </button>
          <button 
            class="px-6 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50"
            @click="next"
            :disabled="currentIndex >= questions.length - 1"
          >
            下一题
          </button>
        </div>
      </div>
    </div>

    <!-- Add to Review Dialog (Reused logic, maybe extract later, but for now duplicate simple version) -->
    <div v-if="showAddToReviewModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-[60]" @click.self="showAddToReviewModal = false">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
          <h3 class="text-lg font-bold text-gray-800 mb-4">加入复盘计划</h3>
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">复盘策略</label>
              <select v-model="reviewPlanType" class="w-full border rounded px-3 py-2">
                <option value="ebbinghaus">艾宾浩斯遗忘曲线</option>
                <option value="daily">每天 (未来30天)</option>
                <option value="weekly">每周 (未来12周)</option>
                <option value="monthly">每月 (未来12月)</option>
                <option value="custom">自定义间隔</option>
              </select>
            </div>
            <div v-if="reviewPlanType === 'custom'">
              <label class="block text-sm font-medium text-gray-700 mb-1">间隔天数</label>
              <input type="number" v-model.number="reviewCustomInterval" class="w-full border rounded px-3 py-2" min="1" />
            </div>
          </div>
          <div class="mt-6 flex justify-end gap-3">
            <button class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded" @click="showAddToReviewModal = false">取消</button>
            <button class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700" @click="confirmAddToReview">确定</button>
          </div>
        </div>
      </div>

  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import api from '../api'
import RichTextEditor from './RichTextEditor.vue'
import { useKnowledgeFolderStore } from '../stores/knowledgeFolders'

const props = defineProps({
  show: Boolean,
  initialFolderId: Number
})

const emit = defineEmits(['close'])

const folderStore = useKnowledgeFolderStore()
const questions = ref([])
const currentIndex = ref(0)
const loading = ref(false)
const filters = ref({
  folderId: props.initialFolderId || null,
  inPlan: null,
  order: 'seq',
  mode: 'browse' // browse | quiz
})

// Quiz state
const userAnswer = ref('')
const submittedAnswer = ref('')
const showAnswer = ref(false)
const submitting = ref(false)

// Review Modal state
const showAddToReviewModal = ref(false)
const reviewPlanType = ref('ebbinghaus')
const reviewCustomInterval = ref(1)

const currentQuestion = computed(() => questions.value[currentIndex.value] || null)

const folderOptions = computed(() => {
  const out = []
  const walk = (nodes, depth) => {
    for (const n of nodes) {
      out.push({ id: n.id, label: `${'\u00A0'.repeat(depth*2)}${n.name}` })
      if (n.children && n.children.length) walk(n.children, depth+1)
    }
  }
  walk(folderStore.tree || [], 0)
  return out
})

const loadQuestions = async () => {
  loading.value = true
  try {
    const params = {
      folder_id: filters.value.folderId || undefined,
      in_plan: filters.value.inPlan,
      order: filters.value.order
    }
    const res = await api.get('/api/brush/questions', { params })
    questions.value = res.data
    currentIndex.value = 0
    resetQuizState()
  } catch (e) {
    alert('加载题目失败')
  } finally {
    loading.value = false
  }
}

const resetQuizState = () => {
  userAnswer.value = ''
  submittedAnswer.value = ''
  showAnswer.value = false
}

const reload = () => {
  loadQuestions()
}

const next = () => {
  if (currentIndex.value < questions.value.length - 1) {
    currentIndex.value++
    resetQuizState()
  }
}

const prev = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--
    resetQuizState()
  }
}

const submitAnswer = async () => {
  if (!userAnswer.value.trim()) return
  submitting.value = true
  try {
    await api.post('/api/brush/answers', {
      knowledge_id: currentQuestion.value.knowledge_id,
      card_id: currentQuestion.value.card_id,
      content: userAnswer.value
    })
    submittedAnswer.value = userAnswer.value
    showAnswer.value = true
  } catch (e) {
    alert('提交失败')
  } finally {
    submitting.value = false
  }
}

const resetQuiz = () => {
  resetQuizState()
}

const close = () => {
  emit('close')
}

// Review Logic
const openAddToReview = () => {
  showAddToReviewModal.value = true
}

const confirmAddToReview = async () => {
  if (!currentQuestion.value) return
  
  const payload = {
    knowledge_id: currentQuestion.value.knowledge_id,
    card_ids: [currentQuestion.value.card_id],
    plan_type: reviewPlanType.value,
    custom_interval: reviewPlanType.value === 'custom' ? reviewCustomInterval.value : undefined
  }
  
  try {
    await api.post('/api/reviews/plan', payload)
    showAddToReviewModal.value = false
    alert('已加入复盘计划')
    // Optionally update local state to reflect it's in plan?
    // But we don't track that in question object explicitly for UI update unless we reload.
  } catch (e) {
    alert('添加失败')
  }
}

watch(() => props.show, (val) => {
  if (val) {
    filters.value.folderId = props.initialFolderId || null
    loadQuestions()
  }
})

onMounted(() => {
  if (!folderStore.tree.length) folderStore.load()
})
</script>
